package com.ibm.cps.api;

import java.util.Collection;

import javax.inject.Named;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.jarxs.ProcessorGroupResource;
import com.ibm.cps.message.MessageFields;
import com.ibm.cps.model.AuthorizationManager;
import com.ibm.cps.model.ServletUtil;
import com.ibm.interfaces.IPersistency;
import com.ibm.mongo.MongoPersistency;
import com.ibm.util.JSONUtility;
import com.ibm.util.exception.CPSException;

@Named
public class ProcessorGroupBean implements ProcessorGroupResource {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private IPersistency persistency;
	private AuthorizationManager authManager;
	
	public ProcessorGroupBean() throws CPSException{
		this.persistency = MongoPersistency.getInstace();
		this.authManager = AuthorizationManager.getInstance();
	}

	@Override
	public Response GetProcessorGroups(String tenantid, UriInfo info, String key) {
		if (!authManager.isAllow(tenantid, key)) {
			String ret = ServletUtil.constructReturnMsg(400, "invalid access");
			return Response.ok(ret,MediaType.APPLICATION_JSON).build();
		}
		ObjectNode filter = JSONUtility.newObjectNode(MessageFields.TENANTID, tenantid);
		try {
			Collection<String> groups = persistency.getProcessorGroups(filter);
			String str = ServletUtil.constructCollectionJson(groups);
			return Response.ok(str, MediaType.APPLICATION_JSON).build();
		} catch (CPSException e) {
			e.printStackTrace();
			String ret = ServletUtil.constructReturnMsg(e.getErrorCode(), e.getErrorMessage());
			return Response.ok(ret).type(MediaType.APPLICATION_JSON).build();
		}
	}

}
